#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
创建丰富的样本数据，用于展示系统各个模块的功能
"""

import os
import sys
from datetime import datetime, timedelta, date
from random import randint, choice, uniform
import json

# 添加应用路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import app, db, User, Project, ProjectTask, ProjectMilestone, ProjectCost, ProjectRole, WeeklyReport, Customer, Contact, FollowUp, CustomerLog, Lead, LeadFollowUp, LeadLog, TaskDependency, Notification

def create_sample_data(force=False):
    """创建丰富的样本数据"""
    with app.app_context():
        print("开始创建样本数据...")
        
        # 1. 创建用户数据
        create_users(force)
        
        # 2. 创建客户数据
        create_customers(force)
        
        # 3. 创建销售线索数据
        create_leads(force)
        
        # 4. 创建项目数据
        create_projects(force)
        
        # 5. 创建项目任务、里程碑和成本数据
        create_project_data(force)
        
        # 6. 创建周报数据
        create_weekly_reports(force)
        
        # 7. 创建通知数据
        create_notifications(force)
        
        print("样本数据创建完成！")

def create_users(force=False):
    """创建用户数据"""
    print("创建用户数据...")
    
    # 检查是否已有用户
    if not force and User.query.count() > 0:
        print("用户数据已存在，跳过创建")
        return
    
    # 如果强制创建，先删除现有数据
    if force:
        User.query.delete()
        db.session.commit()
        print("已删除现有用户数据")
    
    users_data = [
        {"username": "admin", "name": "系统管理员", "role": "admin", "department": "管理部", "position": "系统管理员", "password": "admin"},
        {"username": "zhangsan", "name": "张三", "role": "user", "department": "技术部", "position": "项目经理", "password": "123456"},
        {"username": "lisi", "name": "李四", "role": "user", "department": "技术部", "position": "高级开发工程师", "password": "123456"},
        {"username": "wangwu", "name": "王五", "role": "user", "department": "技术部", "position": "前端开发工程师", "password": "123456"},
        {"username": "zhaoliu", "name": "赵六", "role": "user", "department": "技术部", "position": "后端开发工程师", "password": "123456"},
        {"username": "sunqi", "name": "孙七", "role": "user", "department": "设计部", "position": "UI设计师", "password": "123456"},
        {"username": "zhouba", "name": "周八", "role": "user", "department": "测试部", "position": "测试工程师", "password": "123456"},
        {"username": "wujiu", "name": "吴九", "role": "user", "department": "销售部", "position": "销售经理", "password": "123456"},
        {"username": "chenshi", "name": "陈十", "role": "user", "department": "销售部", "position": "销售代表", "password": "123456"},
        {"username": "lvshi", "name": "吕十一", "role": "user", "department": "市场部", "position": "市场专员", "password": "123456"},
        {"username": "linshier", "name": "林十二", "role": "user", "department": "人事部", "position": "人事专员", "password": "123456"},
        {"username": "huangshisan", "name": "黄十三", "role": "user", "department": "财务部", "position": "财务专员", "password": "123456"}
    ]
    
    for user_data in users_data:
        user = User(
            username=user_data["username"],
            name=user_data["name"],
            role=user_data["role"],
            department=user_data["department"],
            position=user_data["position"]
        )
        user.set_password(user_data["password"])
        db.session.add(user)
    
    db.session.commit()
    print(f"已创建 {len(users_data)} 个用户")

def create_customers(force=False):
    """创建客户数据"""
    print("创建客户数据...")
    
    # 检查是否已有客户
    if not force and Customer.query.count() > 0:
        print("客户数据已存在，跳过创建")
        return
    
    # 如果强制创建，先删除现有数据
    if force:
        # 删除相关数据
        Contact.query.delete()
        FollowUp.query.delete()
        Customer.query.delete()
        db.session.commit()
        print("已删除现有客户数据")
    
    # 获取用户作为负责人
    users = User.query.filter_by(role='user').all()
    if not users:
        print("没有找到用户，请先创建用户")
        return
    
    customers_data = [
        {
            "name": "华为技术有限公司",
            "customer_number": "CUST001",
            "source": "展会",
            "industry": "IT",
            "scale": "大型",
            "type": "成交客户",
            "status": "活跃",
            "address": "深圳市龙岗区坂田华为基地",
            "phone": "0755-28780808",
            "email": "contact@huawei.com",
            "website": "www.huawei.com",
            "estimated_amount": 500000.0,
            "manager_id": choice(users).id
        },
        {
            "name": "腾讯科技有限公司",
            "customer_number": "CUST002",
            "source": "客户介绍",
            "industry": "IT",
            "scale": "大型",
            "type": "成交客户",
            "status": "活跃",
            "address": "深圳市南山区科技园科技中一路腾讯大厦",
            "phone": "0755-86013388",
            "email": "business@tencent.com",
            "website": "www.tencent.com",
            "estimated_amount": 300000.0,
            "manager_id": choice(users).id
        },
        {
            "name": "阿里巴巴集团",
            "customer_number": "CUST003",
            "source": "广告营销",
            "industry": "IT",
            "scale": "大型",
            "type": "意向客户",
            "status": "活跃",
            "address": "杭州市余杭区文一西路969号",
            "phone": "0571-85022088",
            "email": "business@alibaba.com",
            "website": "www.alibaba.com",
            "estimated_amount": 800000.0,
            "manager_id": choice(users).id
        },
        {
            "name": "中国银行",
            "customer_number": "CUST004",
            "source": "公司资源",
            "industry": "金融",
            "scale": "大型",
            "type": "成交客户",
            "status": "活跃",
            "address": "北京市复兴门内大街1号",
            "phone": "010-66596688",
            "email": "service@bankofchina.com",
            "website": "www.boc.cn",
            "estimated_amount": 1000000.0,
            "manager_id": choice(users).id
        },
        {
            "name": "比亚迪股份有限公司",
            "customer_number": "CUST005",
            "source": "销售自拓",
            "industry": "制造",
            "scale": "大型",
            "type": "成交客户",
            "status": "活跃",
            "address": "深圳市坪山区龙田街道龙田社区南布路33号",
            "phone": "0755-89888888",
            "email": "investor@byd.com",
            "website": "www.byd.com",
            "estimated_amount": 600000.0,
            "manager_id": choice(users).id
        },
        {
            "name": "北京大学",
            "customer_number": "CUST006",
            "source": "网站",
            "industry": "教育",
            "scale": "大型",
            "type": "潜在客户",
            "status": "活跃",
            "address": "北京市海淀区颐和园路5号",
            "phone": "010-62751201",
            "email": "info@pku.edu.cn",
            "website": "www.pku.edu.cn",
            "estimated_amount": 200000.0,
            "manager_id": choice(users).id
        },
        {
            "name": "北京协和医院",
            "customer_number": "CUST007",
            "source": "推荐",
            "industry": "医疗",
            "scale": "大型",
            "type": "潜在客户",
            "status": "活跃",
            "address": "北京市东城区东单帅府园1号",
            "phone": "010-69156114",
            "email": "info@pumch.cn",
            "website": "www.pumch.cn",
            "estimated_amount": 300000.0,
            "manager_id": choice(users).id
        },
        {
            "name": "创新科技有限公司",
            "customer_number": "CUST008",
            "source": "网站",
            "industry": "IT",
            "scale": "中型",
            "type": "成交客户",
            "status": "活跃",
            "address": "上海市浦东新区张江高科技园区",
            "phone": "021-12345678",
            "email": "info@innovtech.com",
            "website": "www.innovtech.com",
            "estimated_amount": 150000.0,
            "manager_id": choice(users).id
        }
    ]
    
    for customer_data in customers_data:
        customer = Customer(
            name=customer_data["name"],
            customer_number=customer_data["customer_number"],
            source=customer_data["source"],
            industry=customer_data["industry"],
            scale=customer_data["scale"],
            type=customer_data["type"],
            status=customer_data["status"],
            address=customer_data["address"],
            phone=customer_data["phone"],
            email=customer_data["email"],
            website=customer_data["website"],
            estimated_amount=customer_data["estimated_amount"],
            manager_id=customer_data["manager_id"],
            estimated_close_date=datetime.now() + timedelta(days=choice([30, 60, 90]))
        )
        db.session.add(customer)
        db.session.flush()  # 获取客户ID
        
        # 为每个客户创建联系人
        create_contacts_for_customer(customer.id, users)
        
        # 为每个客户创建跟进记录
        create_followups_for_customer(customer.id, users)
    
    db.session.commit()
    print(f"已创建 {len(customers_data)} 个客户")

def create_contacts_for_customer(customer_id, users):
    """为客户创建联系人"""
    contacts_data = [
        {"name": "张经理", "position": "采购经理", "phone": "13800138001", "email": "zhang@company.com", "gender": "男"},
        {"name": "李总监", "position": "技术总监", "phone": "13800138002", "email": "li@company.com", "gender": "男"},
        {"name": "王助理", "position": "总经理助理", "phone": "13800138003", "email": "wang@company.com", "gender": "女"},
        {"name": "赵专员", "position": "项目经理", "phone": "13800138004", "email": "zhao@company.com", "gender": "女"}
    ]
    
    # 随机选择1-3个联系人
    num_contacts = randint(1, 3)
    selected_contacts = contacts_data[:num_contacts]
    
    for contact_data in selected_contacts:
        contact = Contact(
            name=contact_data["name"],
            position=contact_data["position"],
            phone=contact_data["phone"],
            email=contact_data["email"],
            customer_id=customer_id,
            gender=contact_data["gender"],
            birthday=date(choice([1980, 1985, 1990, 1995]), choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]))
        )
        db.session.add(contact)
    
    db.session.flush()

def create_followups_for_customer(customer_id, users):
    """为客户创建跟进记录"""
    methods = ["电话", "邮件", "会面", "微信"]
    contents = [
        "初步了解客户需求",
        "介绍公司产品和服务",
        "发送产品资料和报价单",
        "讨论技术方案细节",
        "确认合作意向",
        "商讨合同条款",
        "跟进项目进度",
        "客户满意度调查"
    ]
    results = [
        "客户表示有兴趣，需要进一步了解",
        "已发送详细资料，等待客户反馈",
        "客户对产品表示满意，正在考虑采购",
        "已确定合作意向，准备签订合同",
        "合同已签订，项目即将启动",
        "客户对项目进展表示满意",
        "客户提出了一些改进建议",
        "客户表示愿意长期合作"
    ]
    
    # 创建1-5条跟进记录
    num_followups = randint(1, 5)
    for i in range(num_followups):
        followup_date = datetime.now() - timedelta(days=randint(1, 30))
        next_followup_date = followup_date + timedelta(days=randint(3, 14))
        
        followup = FollowUp(
            customer_id=customer_id,
            contact_id=choice(Contact.query.filter_by(customer_id=customer_id).all()).id,
            manager_id=choice(users).id,
            method=choice(methods),
            content=choice(contents),
            result=choice(results),
            next_followup_time=next_followup_date if i < num_followups - 1 else None,
            created_at=followup_date
        )
        db.session.add(followup)
    
    db.session.flush()

def create_leads(force=False):
    """创建销售线索数据"""
    print("创建销售线索数据...")
    
    # 检查是否已有线索
    if not force and Lead.query.count() > 0:
        print("销售线索数据已存在，跳过创建")
        return
    
    # 如果强制创建，先删除现有数据
    if force:
        # 删除相关数据
        LeadFollowUp.query.delete()
        Lead.query.delete()
        db.session.commit()
        print("已删除现有销售线索数据")
    
    # 获取用户作为负责人和创建人
    users = User.query.filter_by(role='user').all()
    if not users:
        print("没有找到用户，请先创建用户")
        return
    
    leads_data = [
        {
            "name": "刘经理",
            "phone": "13900139001",
            "email": "liu@company.com",
            "company": "新创科技有限公司",
            "position": "技术总监",
            "source": "网站",
            "industry": "IT",
            "budget": 200000.0,
            "status": "新线索",
            "score": 70,
            "assigned_to": choice(users).id,
            "created_by": choice(users).id
        },
        {
            "name": "陈总",
            "phone": "13900139002",
            "email": "chen@company.com",
            "company": "未来智能科技",
            "position": "CEO",
            "source": "展会",
            "industry": "IT",
            "budget": 500000.0,
            "status": "跟进中",
            "score": 85,
            "assigned_to": choice(users).id,
            "created_by": choice(users).id,
            "assigned_at": datetime.now() - timedelta(days=2)
        },
        {
            "name": "王主任",
            "phone": "13900139003",
            "email": "wang@company.com",
            "company": "智慧医疗系统",
            "position": "信息中心主任",
            "source": "推荐",
            "industry": "医疗",
            "budget": 300000.0,
            "status": "跟进中",
            "score": 90,
            "assigned_to": choice(users).id,
            "created_by": choice(users).id,
            "assigned_at": datetime.now() - timedelta(days=5),
            "first_contact_at": datetime.now() - timedelta(days=3)
        },
        {
            "name": "张经理",
            "phone": "13900139004",
            "email": "zhang@company.com",
            "company": "金融科技服务",
            "position": "产品经理",
            "source": "电话",
            "industry": "金融",
            "budget": 800000.0,
            "status": "已转化",
            "score": 95,
            "assigned_to": choice(users).id,
            "created_by": choice(users).id,
            "assigned_at": datetime.now() - timedelta(days=10),
            "first_contact_at": datetime.now() - timedelta(days=8),
            "converted_at": datetime.now() - timedelta(days=2)
        },
        {
            "name": "李总",
            "phone": "13900139005",
            "email": "li@company.com",
            "company": "教育科技公司",
            "position": "创始人",
            "source": "客户介绍",
            "industry": "教育",
            "budget": 150000.0,
            "status": "已关闭",
            "score": 60,
            "assigned_to": choice(users).id,
            "created_by": choice(users).id,
            "assigned_at": datetime.now() - timedelta(days=15),
            "first_contact_at": datetime.now() - timedelta(days=12)
        }
    ]
    
    for lead_data in leads_data:
        lead = Lead(
            name=lead_data["name"],
            phone=lead_data["phone"],
            email=lead_data["email"],
            company=lead_data["company"],
            position=lead_data["position"],
            source=lead_data["source"],
            industry=lead_data["industry"],
            budget=lead_data["budget"],
            status=lead_data["status"],
            score=lead_data["score"],
            assigned_to=lead_data["assigned_to"],
            created_by=lead_data["created_by"],
            estimated_amount=lead_data["budget"],
            estimated_close_date=datetime.now() + timedelta(days=choice([30, 60, 90])),
            conversion_notes="客户对我们的产品很感兴趣，认为能够解决他们的痛点" if lead_data["status"] == "已转客户" else None
        )
        
        if "assigned_at" in lead_data:
            lead.assigned_at = lead_data["assigned_at"]
        if "first_contact_at" in lead_data:
            lead.first_contact_at = lead_data["first_contact_at"]
        if "converted_at" in lead_data:
            lead.converted_at = lead_data["converted_at"]
            
        db.session.add(lead)
        db.session.flush()  # 获取线索ID
        
        # 为线索创建跟进记录
        create_lead_followups(lead.id, users)
    
    db.session.commit()
    print(f"已创建 {len(leads_data)} 个销售线索")

def create_lead_followups(lead_id, users):
    """为线索创建跟进记录"""
    methods = ["电话", "邮件", "会面", "微信"]
    contents = [
        "初步联系，了解客户需求",
        "发送公司介绍和产品资料",
        "详细沟通技术方案",
        "提供报价和合作方案",
        "跟进客户反馈",
        "协商合同细节"
    ]
    results = [
        "客户表示有兴趣，需要进一步了解",
        "已发送详细资料，等待客户反馈",
        "客户对产品表示满意，正在考虑采购",
        "已确定合作意向，准备签订合同",
        "合同已签订，项目即将启动"
    ]
    
    # 创建1-3条跟进记录
    num_followups = randint(1, 3)
    for i in range(num_followups):
        followup_date = datetime.now() - timedelta(days=randint(1, 30))
        next_followup_date = followup_date + timedelta(days=randint(3, 14))
        
        followup = LeadFollowUp(
            lead_id=lead_id,
            manager_id=choice(users).id,
            method=choice(methods),
            content=choice(contents),
            result=choice(results),
            next_followup_time=next_followup_date if i < num_followups - 1 else None,
            created_at=followup_date
        )
        db.session.add(followup)
    
    db.session.flush()

def create_projects(force=False):
    """创建项目数据"""
    print("创建项目数据...")
    
    # 检查是否已有项目
    if not force and Project.query.count() > 0:
        print("项目数据已存在，跳过创建")
        return
    
    # 如果强制创建，先删除现有数据
    if force:
        # 删除相关数据
        ProjectRole.query.delete()
        Project.query.delete()
        db.session.commit()
        print("已删除现有项目数据")
    
    # 获取用户和客户
    users = User.query.filter_by(role='user').all()
    customers = Customer.query.filter_by(type='成交客户').all()
    
    if not users or not customers:
        print("没有找到足够的用户或客户，请先创建")
        return
    
    project_types = ['产品研发', '产品设计', '工程项目', '软件交付', '技术咨询']
    project_sources = ['公开招标', '广告营销', '客户介绍', '朋友介绍', '公司资源', '销售自拓']
    risk_levels = ['低', '中', '高']
    
    projects_data = [
        {
            "name": "企业管理系统开发",
            "description": "为华为公司开发一套完整的企业管理系统，包括人力资源、财务、项目管理等模块",
            "project_type": "软件交付",
            "project_source": "公开招标",
            "budget": 500000.0,
            "risk_level": "中",
            "customer_id": customers[0].id if len(customers) > 0 else None,
            "manager_id": users[0].id if len(users) > 0 else None,
            "start_date": datetime.now() - timedelta(days=30),
            "end_date": datetime.now() + timedelta(days=60),
            "status": "进行中",
            "progress": 45
        },
        {
            "name": "移动应用UI设计",
            "description": "为腾讯公司的移动应用提供全套UI设计方案",
            "project_type": "产品设计",
            "project_source": "客户介绍",
            "budget": 200000.0,
            "risk_level": "低",
            "customer_id": customers[1].id if len(customers) > 1 else None,
            "manager_id": users[1].id if len(users) > 1 else None,
            "start_date": datetime.now() - timedelta(days=15),
            "end_date": datetime.now() + timedelta(days=30),
            "status": "进行中",
            "progress": 70
        },
        {
            "name": "电商平台开发",
            "description": "为阿里巴巴集团开发一个新的电商平台",
            "project_type": "产品研发",
            "project_source": "广告营销",
            "budget": 800000.0,
            "risk_level": "高",
            "customer_id": customers[2].id if len(customers) > 2 else None,
            "manager_id": users[2].id if len(users) > 2 else None,
            "start_date": datetime.now() + timedelta(days=15),
            "end_date": datetime.now() + timedelta(days=120),
            "status": "未开始",
            "progress": 0
        },
        {
            "name": "银行系统升级",
            "description": "为中国银行进行现有银行系统的升级和改造",
            "project_type": "工程项目",
            "project_source": "公司资源",
            "budget": 1000000.0,
            "risk_level": "高",
            "customer_id": customers[3].id if len(customers) > 3 else None,
            "manager_id": users[3].id if len(users) > 3 else None,
            "start_date": datetime.now() - timedelta(days=60),
            "end_date": datetime.now() - timedelta(days=10),
            "status": "已完成",
            "progress": 100
        },
        {
            "name": "智能制造解决方案",
            "description": "为比亚迪公司提供智能制造的整体解决方案",
            "project_type": "技术咨询",
            "project_source": "销售自拓",
            "budget": 600000.0,
            "risk_level": "中",
            "customer_id": customers[4].id if len(customers) > 4 else None,
            "manager_id": users[4].id if len(users) > 4 else None,
            "start_date": datetime.now() - timedelta(days=45),
            "end_date": datetime.now() + timedelta(days=15),
            "status": "进行中",
            "progress": 85
        },
        {
            "name": "教育平台开发",
            "description": "为北京大学开发在线教育平台",
            "project_type": "软件交付",
            "project_source": "公开招标",
            "budget": 300000.0,
            "risk_level": "低",
            "customer_id": customers[5].id if len(customers) > 5 else None,
            "manager_id": users[5].id if len(users) > 5 else None,
            "start_date": datetime.now() - timedelta(days=20),
            "end_date": datetime.now() + timedelta(days=40),
            "status": "进行中",
            "progress": 30
        }
    ]
    
    for i, project_data in enumerate(projects_data):
        project = Project(
            name=project_data["name"],
            description=project_data["description"],
            project_type=project_data["project_type"],
            project_source=project_data["project_source"],
            budget=project_data["budget"],
            risk_level=project_data["risk_level"],
            customer_id=project_data["customer_id"],
            manager_id=project_data["manager_id"],
            start_date=project_data["start_date"],
            end_date=project_data["end_date"],
            status=project_data["status"],
            progress=project_data["progress"],
            project_number=f"PRJ-{2023}-{i+1:03d}",
            project_code=f"PC{2023}{i+1:03d}"
        )
        db.session.add(project)
        db.session.flush()  # 获取项目ID
        
        # 为项目添加团队成员
        create_project_team(project.id, users)
    
    db.session.commit()
    print(f"已创建 {len(projects_data)} 个项目")

def create_project_team(project_id, users):
    """为项目创建团队"""
    roles = ['项目经理', '开发工程师', 'UI设计师', '测试工程师', '产品经理']
    
    # 随机选择3-5个用户作为团队成员
    num_members = randint(3, 5)
    selected_users = users[:num_members]
    
    for i, user in enumerate(selected_users):
        role = ProjectRole(
            project_id=project_id,
            user_id=user.id,
            role=roles[i] if i < len(roles) else '开发工程师'
        )
        db.session.add(role)
    
    db.session.flush()

def create_project_data(force=False):
    """为项目创建任务、里程碑和成本数据"""
    print("创建项目任务、里程碑和成本数据...")
    
    # 如果强制创建，先删除现有数据
    if force:
        # 删除相关数据
        TaskDependency.query.delete()
        ProjectCost.query.delete()
        ProjectMilestone.query.delete()
        ProjectTask.query.delete()
        db.session.commit()
        print("已删除现有项目任务、里程碑和成本数据")
    
    # 获取所有项目
    projects = Project.query.all()
    if not projects:
        print("没有找到项目，请先创建项目")
        return
    
    # 获取所有用户
    users = User.query.all()
    if not users:
        print("没有找到用户，请先创建用户")
        return
    
    for project in projects:
        # 创建项目里程碑
        create_project_milestones(project.id)
        
        # 创建项目任务
        create_project_tasks(project.id, users)
        
        # 创建项目成本
        create_project_costs(project.id)
    
    db.session.commit()
    print(f"已为 {len(projects)} 个项目创建任务、里程碑和成本数据")

def create_project_milestones(project_id):
    """创建项目里程碑"""
    project = Project.query.get(project_id)
    if not project:
        return
    
    # 计算项目总天数
    total_days = (project.end_date - project.start_date).days
    
    # 创建里程碑
    milestone_dates = [
        project.start_date + timedelta(days=int(total_days * 0.2)),
        project.start_date + timedelta(days=int(total_days * 0.4)),
        project.start_date + timedelta(days=int(total_days * 0.6)),
        project.start_date + timedelta(days=int(total_days * 0.8)),
        project.end_date
    ]
    
    milestone_names = ["需求确认", "设计评审", "开发完成", "测试通过", "项目交付"]
    
    for i, (name, date) in enumerate(zip(milestone_names, milestone_dates)):
        # 根据项目进度设置里程碑状态
        if project.progress >= (i + 1) * 20:
            status = "已完成"
        elif project.progress >= i * 20:
            status = "进行中"
        else:
            status = "未开始"
            
        milestone = ProjectMilestone(
            project_id=project_id,
            name=name,
            description=f"{name}里程碑",
            due_date=date.date(),
            status=status
        )
        db.session.add(milestone)
    
    db.session.flush()

def create_project_tasks(project_id, users):
    """创建项目任务"""
    project = Project.query.get(project_id)
    if not project:
        return
    
    # 创建项目阶段任务
    phases = [
        {"name": "需求分析", "duration": 10, "progress": 100},
        {"name": "系统设计", "duration": 15, "progress": 80},
        {"name": "开发实现", "duration": 30, "progress": 50},
        {"name": "测试验证", "duration": 15, "progress": 20},
        {"name": "部署上线", "duration": 5, "progress": 0}
    ]
    
    # 根据项目进度调整阶段进度
    for phase in phases:
        if project.progress >= 100:
            phase["progress"] = 100
        elif project.progress >= 80:
            if phase["name"] in ["需求分析", "系统设计"]:
                phase["progress"] = 100
            elif phase["name"] == "开发实现":
                phase["progress"] = 90
            elif phase["name"] == "测试验证":
                phase["progress"] = 60
        elif project.progress >= 60:
            if phase["name"] in ["需求分析", "系统设计"]:
                phase["progress"] = 100
            elif phase["name"] == "开发实现":
                phase["progress"] = 70
            elif phase["name"] == "测试验证":
                phase["progress"] = 10
        elif project.progress >= 40:
            if phase["name"] == "需求分析":
                phase["progress"] = 100
            elif phase["name"] == "系统设计":
                phase["progress"] = 80
            elif phase["name"] == "开发实现":
                phase["progress"] = 30
        elif project.progress >= 20:
            if phase["name"] == "需求分析":
                phase["progress"] = 100
            elif phase["name"] == "系统设计":
                phase["progress"] = 40
    
    # 创建阶段任务
    current_date = project.start_date
    task_dependencies = {}  # 用于存储任务依赖关系
    
    for i, phase in enumerate(phases):
        # 计算阶段开始和结束日期
        phase_start = current_date
        phase_end = phase_start + timedelta(days=phase["duration"])
        
        # 创建主任务
        main_task = ProjectTask(
            project_id=project_id,
            name=phase["name"],
            description=f"{phase['name']}阶段",
            start_date=phase_start,
            end_date=phase_end,
            progress=phase["progress"],
            status="已完成" if phase["progress"] == 100 else ("进行中" if phase["progress"] > 0 else "未开始"),
            priority="高" if i < 2 else "中",
            work_hour=phase["duration"] * 8,
            task_code=f"{project.project_code}-T{i+1:03d}" if project.project_code else f"TASK-{i+1:03d}"
        )
        db.session.add(main_task)
        db.session.flush()  # 获取任务ID
        
        # 存储任务ID，用于创建依赖关系
        task_dependencies[f"phase_{i}"] = main_task.id
        
        # 为每个阶段创建子任务
        subtasks = []
        if phase["name"] == "需求分析":
            subtasks = [
                {"name": "需求收集", "duration": 3, "progress": 100},
                {"name": "需求分析", "duration": 4, "progress": 100},
                {"name": "需求文档编写", "duration": 3, "progress": 100}
            ]
        elif phase["name"] == "系统设计":
            subtasks = [
                {"name": "架构设计", "duration": 5, "progress": 100},
                {"name": "数据库设计", "duration": 4, "progress": 80},
                {"name": "UI设计", "duration": 6, "progress": 60}
            ]
        elif phase["name"] == "开发实现":
            subtasks = [
                {"name": "前端开发", "duration": 15, "progress": 60},
                {"name": "后端开发", "duration": 18, "progress": 50},
                {"name": "接口开发", "duration": 10, "progress": 40}
            ]
        elif phase["name"] == "测试验证":
            subtasks = [
                {"name": "单元测试", "duration": 5, "progress": 30},
                {"name": "集成测试", "duration": 5, "progress": 20},
                {"name": "用户验收测试", "duration": 5, "progress": 10}
            ]
        elif phase["name"] == "部署上线":
            subtasks = [
                {"name": "环境准备", "duration": 2, "progress": 0},
                {"name": "系统部署", "duration": 2, "progress": 0},
                {"name": "上线验证", "duration": 1, "progress": 0}
            ]
        
        # 根据项目进度调整子任务进度
        for subtask in subtasks:
            if phase["progress"] >= 100:
                subtask["progress"] = 100
            elif phase["progress"] >= 80:
                subtask["progress"] = min(100, subtask["progress"] + 20)
            elif phase["progress"] >= 60:
                subtask["progress"] = min(100, subtask["progress"] + 10)
            elif phase["progress"] >= 40:
                subtask["progress"] = max(0, subtask["progress"] - 10)
            elif phase["progress"] >= 20:
                subtask["progress"] = max(0, subtask["progress"] - 20)
        
        # 创建子任务
        subtask_start = phase_start
        for j, subtask in enumerate(subtasks):
            subtask_end = subtask_start + timedelta(days=subtask["duration"])
            
            task = ProjectTask(
                project_id=project_id,
                name=subtask["name"],
                description=f"{phase['name']} - {subtask['name']}",
                start_date=subtask_start,
                end_date=subtask_end,
                progress=subtask["progress"],
                status="已完成" if subtask["progress"] == 100 else ("进行中" if subtask["progress"] > 0 else "未开始"),
                priority=choice(["高", "中", "低"]),
                work_hour=subtask["duration"] * 8,
                parent_id=main_task.id,
                assignee_id=choice(users).id,
                task_code=f"{project.project_code}-T{i+1:03d}-{j+1:02d}" if project.project_code else f"TASK-{i+1:03d}-{j+1:02d}"
            )
            db.session.add(task)
            db.session.flush()  # 获取任务ID
            
            # 创建任务依赖关系
            if i > 0 and j == 0:  # 每个阶段的第一个子任务依赖于上一阶段的最后一个子任务
                dependency = TaskDependency(
                    task_id=task.id,
                    depends_on_id=task_dependencies[f"phase_{i-1}"]
                )
                db.session.add(dependency)
            
            # 更新下一个子任务的开始日期
            subtask_start = subtask_end + timedelta(days=1)
        
        # 更新下一个阶段的开始日期
        current_date = phase_end + timedelta(days=1)
    
    db.session.flush()

def create_project_costs(project_id):
    """创建项目成本"""
    project = Project.query.get(project_id)
    if not project:
        return
    
    cost_types = ["人工成本", "材料成本", "设备成本", "外包成本", "其他成本"]
    
    # 创建3-5条成本记录
    num_costs = randint(3, 5)
    for i in range(num_costs):
        # 根据项目进度设置成本日期
        cost_date = project.start_date + timedelta(days=randint(1, (project.end_date - project.start_date).days))
        
        cost = ProjectCost(
            project_id=project_id,
            cost_type=choice(cost_types),
            amount=round(uniform(1000.0, 50000.0), 2),
            description=f"{choice(cost_types)} - 项目{i+1}",
            record_date=cost_date.date()
        )
        db.session.add(cost)
    
    db.session.flush()

def create_weekly_reports(force=False):
    """创建周报数据"""
    print("创建周报数据...")
    
    # 检查是否已有周报
    if not force and WeeklyReport.query.count() > 0:
        print("周报数据已存在，跳过创建")
        return
    
    # 如果强制创建，先删除现有数据
    if force:
        WeeklyReport.query.delete()
        db.session.commit()
        print("已删除现有周报数据")
    
    # 获取所有项目和用户
    projects = Project.query.filter(Project.status.in_(['进行中', '已完成'])).all()
    users = User.query.filter_by(role='user').all()
    
    if not projects or not users:
        print("没有找到足够的项目或用户，请先创建")
        return
    
    # 为每个进行中的项目创建周报
    for project in projects:
        # 获取项目团队成员
        team_members = [role.user for role in ProjectRole.query.filter_by(project_id=project.id).all()]
        
        if not team_members:
            continue
        
        # 计算项目天数
        project_days = (datetime.now().date() - project.start_date.date()).days
        if project_days <= 0:
            continue
        
        # 创建最近4周的周报
        for weeks_ago in range(min(4, project_days // 7)):
            # 计算周开始日期（周一）
            week_start_date = datetime.now().date() - timedelta(days=weeks_ago * 7)
            # 调整到本周一
            week_start_date = week_start_date - timedelta(days=week_start_date.weekday())
            # 计算周结束日期（周日）
            week_end_date = week_start_date + timedelta(days=6)
            
            # 为每个团队成员创建周报
            for member in team_members:
                # 随机决定是否创建周报（80%概率）
                if randint(1, 100) <= 80:
                    weekly_work_hours = round(uniform(30.0, 50.0), 1)
                    
                    # 根据项目进度生成工作内容
                    work_contents = [
                        "完成了用户管理模块的开发和测试",
                        "修复了系统中的多个bug并进行了性能优化",
                        "与客户进行了需求沟通并确认了下一阶段的工作计划",
                        "编写了技术文档和用户手册",
                        "进行了代码审查和重构",
                        "完成了数据库设计和优化",
                        "开发了新的API接口并编写了测试用例",
                        "优化了系统性能，提高了响应速度",
                        "完成了单元测试和集成测试",
                        "参与了项目评审会议和客户演示"
                    ]
                    
                    next_week_plans = [
                        "继续开发用户权限管理模块",
                        "进行系统性能优化和安全加固",
                        "与客户进行需求确认和原型评审",
                        "完成剩余功能的开发和测试",
                        "准备项目上线和部署文档",
                        "进行用户培训和系统交接",
                        "编写技术文档和用户手册",
                        "修复测试中发现的问题",
                        "准备项目验收材料",
                        "进行项目总结和经验分享"
                    ]
                    
                    weekly_issues = [
                        "暂无风险与问题",
                        "第三方接口存在兼容性问题，正在协调解决",
                        "客户需求变更频繁，可能影响项目进度",
                        "技术团队人员不足，需要加强资源投入",
                        "系统性能有待优化，计划下周进行专项优化",
                        "部分模块测试覆盖率不足，需要补充测试用例",
                        "项目进度略有延迟，已制定追赶计划",
                        "客户反馈部分功能不符合预期，需要调整",
                        "技术难点攻关时间超出预期",
                        "项目资源紧张，需要协调更多人力"
                    ]
                    
                    report = WeeklyReport(
                        project_id=project.id,
                        user_id=member.id,
                        week_start_date=week_start_date,
                        week_end_date=week_end_date,
                        weekly_work_hours=weekly_work_hours,
                        weekly_work_content=choice(work_contents),
                        next_week_plan=choice(next_week_plans),
                        weekly_issues=choice(weekly_issues)
                    )
                    db.session.add(report)
    
    db.session.commit()
    print("周报数据创建完成")

def create_notifications(force=False):
    """创建通知数据"""
    print("创建通知数据...")
    
    # 检查是否已有通知
    if not force and Notification.query.count() > 0:
        print("通知数据已存在，跳过创建")
        return
    
    # 如果强制创建，先删除现有数据
    if force:
        Notification.query.delete()
        db.session.commit()
        print("已删除现有通知数据")
    
    # 获取所有用户
    users = User.query.all()
    if not users:
        print("没有找到用户，请先创建用户")
        return
    
    notification_types = ["系统通知", "任务提醒", "里程碑预警", "项目更新", "客户跟进"]
    
    # 为每个用户创建3-5条通知
    for user in users:
        num_notifications = randint(3, 5)
        
        for i in range(num_notifications):
            # 随机决定通知是否已读（已读概率60%）
            is_read = randint(1, 100) <= 60
            
            # 根据通知类型生成标题和内容
            notification_type = choice(notification_types)
            
            if notification_type == "系统通知":
                title = "系统维护通知"
                content = "系统将于本周六晚上进行例行维护，预计持续2小时，请提前做好准备。"
            elif notification_type == "任务提醒":
                title = "任务即将到期"
                content = "您负责的任务'系统设计'将于3天后到期，请及时完成相关工作。"
            elif notification_type == "里程碑预警":
                title = "里程碑即将到期"
                content = "项目'企业管理系统开发'的里程碑'设计评审'将于5天后到期，请确保相关工作按时完成。"
            elif notification_type == "项目更新":
                title = "项目状态更新"
                content = "您参与的项目'移动应用UI设计'状态已更新为'进行中'，当前进度为70%。"
            else:  # 客户跟进
                title = "客户跟进提醒"
                content = "客户'华为技术有限公司'的下次跟进时间为明天，请提前准备相关材料。"
            
            # 随机生成创建时间（最近7天内）
            created_at = datetime.now() - timedelta(days=randint(0, 7), hours=randint(0, 23), minutes=randint(0, 59))
            
            notification = Notification(
                user_id=user.id,
                title=title,
                content=content,
                notification_type=notification_type,
                is_read=is_read,
                created_at=created_at
            )
            db.session.add(notification)
    
    db.session.commit()
    print(f"已为 {len(users)} 个用户创建通知数据")

if __name__ == '__main__':
    import sys
    force = False
    if len(sys.argv) > 1 and sys.argv[1] == '--force':
        force = True
        print("强制重新创建所有数据...")
    
    create_sample_data(force)